<template>
  <div class="warehouse-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <el-icon class="header-icon">
            <Box />
          </el-icon>
          <h1 class="page-title">仓库入库管理</h1>
        </div>
        <div class="header-right">
          <span class="page-subtitle">出入库流水管理</span>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 搜索条件卡片 -->
      <el-card class="search-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon>
              <Search />
            </el-icon>
            <span>查询条件</span>
          </div>
        </template>

        <el-form :inline="true" :model="formInline" class="search-form">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="出入库单号">
                <el-input v-model="formInline.Warehouse_Code" placeholder="请输入出库单号/入库单号" clearable class="custom-input">
                  <template #prefix>
                    <el-icon>
                      <Document />
                    </el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="仓库名称">
                <el-select v-model="formInline.Warehouse_ID" placeholder="请选择" clearable class="custom-select">
                  <el-option v-for="item in deplarment" :label="item.warehouse_Name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务类型">
                <el-select v-model="formInline.Warehousing_Type" placeholder="请选择" clearable class="custom-select">
                  <el-option label="采购收货入库" value="采购收货入库" />
                  <el-option label="销售退货入库" value="销售退货入库" />
                  <el-option label="生产入库" value="生产入库" />
                  <el-option label="换货入库" value="换货入库" />
                  <el-option label="盘盈入库" value="盘盈入库" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出入库类型">
                <el-select v-model="formInline.Warehousing_Type" placeholder="请选择" clearable class="custom-select">
                  <el-option label="进货入库" value="进货入库" />
                  <el-option label="销售出库" value="销售出库" />
                  <el-option label="调拨入库" value="调拨入库" />
                  <el-option label="调拨出库" value="调拨出库" />
                  <el-option label="退货入库" value="退货入库" />
                  <el-option label="退货出库" value="退货出库" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="出入库日期">
                <el-date-picker v-model="formInline.ReviewTimeStartTime" type="date" placeholder="请选择"
                  style="width: 100%" class="custom-date-picker" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="制单日期">
                <el-date-picker v-model="formInline.CreateTimeStartTime" type="date" placeholder="请选择"
                  style="width: 100%" class="custom-date-picker" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" @click="getdata()" class="search-btn">
                  <el-icon>
                    <Search />
                  </el-icon>
                  查询
                </el-button>
                <el-button @click="resetForm" class="reset-btn">
                  <el-icon>
                    <Refresh />
                  </el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-card class="stats-card inbound-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">{{ totalInboundCount }}</div>
            <div class="stats-label">入库数量</div>
          </div>
          <div class="stats-icon">
            <el-icon>
              <ArrowDown />
            </el-icon>
          </div>
        </el-card>

        <el-card class="stats-card inbound-amount-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-number">¥{{ totalInboundAmount }}</div>
            <div class="stats-label">入库金额</div>
          </div>
          <div class="stats-icon">
            <el-icon>
              <Money />
            </el-icon>
          </div>
        </el-card>
      </div>

      <!-- 数据表格卡片 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon>
              <List />
            </el-icon>
            <span>出入库流水</span>
            <div class="header-actions">
              <el-button type="success" @click="handleExport()" class="export-btn">
                <el-icon>
                  <Download />
                </el-icon>
                导出
              </el-button>
              <el-button type="primary" @click="getdata()" class="refresh-btn">
                <el-icon>
                  <Refresh />
                </el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table :data="tableData" style="width: 100%" class="custom-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="warehouse_Code" label="序号" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="warehouse_Code" label="出入库单号" width="150" />
          <el-table-column prop="reviewTime" label="出入库日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.reviewTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="warehouseType" label="业务类型" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.warehouseType == 1 ? 'success' : 'danger'" size="small">
                {{ scope.row.warehouseType == 1 ? '入库' : '出库' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="warehousing_Type" label="出入库类型" width="120" />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="100" />
          <el-table-column prop="warehouse_InOrOutCount" label="入库数量" width="100">
            <template #default="scope">
              <span v-if="scope.row.warehouseType == 1" class="inbound-count">
                {{ scope.row.warehouse_InOrOutCount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="warehouse_InOrOutCount" label="出库数量" width="100">
            <template #default="scope">
              <span v-if="scope.row.warehouseType != 1" class="outbound-count">
                {{ scope.row.warehouse_InOrOutCount }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="total_Price" label="入库金额" width="120">
            <template #default="scope">
              <span v-if="scope.row.warehouseType == 1" class="inbound-amount">
                ¥{{ scope.row.total_Price }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="total_Price" label="出库金额" width="120">
            <template #default="scope">
              <span v-if="scope.row.warehouseType != 1" class="outbound-amount">
                ¥{{ scope.row.total_Price }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="reviewer" label="经办人" width="100" />
          <el-table-column prop="createUse" label="制单人" width="100">
            <template #default="scope">
              <span v-if="scope.row.createUse == '10032'">吴维昊</span>
              <span v-if="scope.row.createUse == '10036'">王雨龙</span>
              <span v-if="scope.row.createUse == '10037'">张可欣</span>
              <span v-if="scope.row.createUse == '10038'">赵姝雅</span>
              <span v-if="scope.row.createUse == '10039'">段栋兴</span>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="所在部门" width="100">
            <template #default>
              仓储部
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="制单" width="120">
            <template #default>
              2025-08-02
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]" layout="total, sizes, prev, pager, next, jumper" prev-text="上一页"
            next-text="下一页" :total="page.totalCount" class="custom-pagination" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { reactive, onMounted, ref, watch, computed } from 'vue'

import { ElMessage, ElMessageBox } from 'element-plus'
import { BasicsWrite } from '@/http/axiosHelper'
import { useRouter } from 'vue-router'
import { statementRed } from '@/http/axiosHelper'
import {
  Box,
  Search,
  Document,
  Refresh,
  ArrowDown,
  ArrowUp,
  Money,
  List,
  Download
} from '@element-plus/icons-vue'

const router = useRouter();
const dialogVisible = ref(false)

function formatDate(dateStr: string) {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

const AddWarehouse = () => {
  router.push('/AddWarehouse')
}

const UpdateWarehouse = (id: any) => {
  router.push({ path: "/UpdateWarehouse", query: { id: id } })
}

// 重置表单
const resetForm = () => {
  Object.assign(formInline, {
    Warehouse_Code: '',
    Warehousing_Type: '',
    Warehouse_ID: null,
    Reviewer: '',
    Product_Name: '',
    Category_ID: null,
    Unit_ID: null,
    CreateTimeStartTime: null,
    CreateTimeEndTime: null,
    ReviewTimeStartTime: null,
    ReviewTimeEndTime: null,
    CreateUse: null
  })
  ElMessage.success('查询条件已重置')
}

const handleClose = (done: () => void) => {
  ElMessageBox.confirm('Are you sure to close this dialog?')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

const formInline = reactive({
  Warehouse_Code: '',
  Warehousing_Type: '',
  Warehouse_ID: null,
  Reviewer: '',
  Product_Name: '',
  Category_ID: null,
  Unit_ID: null,
  CreateTimeStartTime: null,
  CreateTimeEndTime: null,
  ReviewTimeStartTime: null,
  ReviewTimeEndTime: null,
  CreateUse: null
})

const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0
})

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
  try {
    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await statementRed({
      url: 'api/Warehouse_InOrOut/GetWarehouse_InExport', // 后端接口地址
      method: 'GET',
      params: {
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
        Category_ID: formInline.Category_ID,
        CreateTimeStartTime: formInline.CreateTimeStartTime,
        CreateTimeEndTime: formInline.CreateTimeEndTime,
        CreateUse: formInline.CreateUse,
        Product_Name: formInline.Product_Name,
        ReviewTimeEndTime: formInline.ReviewTimeEndTime,
        ReviewTimeStartTime: formInline.ReviewTimeStartTime,
        Reviewer: formInline.Reviewer,
        Unit_ID: formInline.Unit_ID,
        Warehouse_Code: formInline.Warehouse_Code,
        Warehouse_ID: formInline.Warehouse_ID,
        Warehousing_Type: formInline.Warehousing_Type
      }, // 对应后端 [FromQuery] 的 command 参数
      responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success('导出成功')

  } catch (error: any) {
    // 处理错误（如后端返回 401/400 等）
    console.error('导出失败：', error.response?.data || error.message);
    ElMessage.error('导出失败，请检查参数或重新登录');
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
  const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
  if (!contentDisposition) return '入库流水.xlsx'; // 默认文件名

  // 解码文件名（处理中文编码问题）
  const match = contentDisposition.match(/filename\*?=([^;]+)/);
  if (match) {
    return decodeURIComponent(match[1].replace(/["']/g, ''));
  }
  return '入库流水.xlsx';
}

const page2 = reactive({
  PageIndex: 1,
  PageSize: 100,
  totalCount: 0
})

watch(page, () => {
  getdata();
})

onMounted(() => {
  delparmentdata();
  getdata();
})

const del = (id: any) => {
  ElMessageBox.confirm(
    '确认删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      statementRed.put("basicswrite/api/Warehouse/DelwarehouseHandle", { id: id }).then(res => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          getdata();
        }
        else {
          ElMessage.success("删除失败");
        }
      }
      )
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

const deplarment = ref()
const delparmentdata = () => {
  statementRed.get("api/Inventory/GetWarehouse").then(res => {
    deplarment.value = res.data.data
  }
  )
}

const tableData = ref([]);

const getdata = () => {
  statementRed.get("api/Warehouse_InOrOut/GetWarehouse_InOrOutHandle", {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize,
      Category_ID: formInline.Category_ID,
      CreateTimeStartTime: formInline.CreateTimeStartTime,
      CreateTimeEndTime: formInline.CreateTimeEndTime,
      CreateUse: formInline.CreateUse,
      Product_Name: formInline.Product_Name,
      ReviewTimeEndTime: formInline.ReviewTimeEndTime,
      ReviewTimeStartTime: formInline.ReviewTimeStartTime,
      Reviewer: formInline.Reviewer,
      Unit_ID: formInline.Unit_ID,
      Warehouse_Code: formInline.Warehouse_Code,
      Warehouse_ID: formInline.Warehouse_ID,
      Warehousing_Type: formInline.Warehousing_Type,
    }
  }).then(res => {
    tableData.value = res.data.data
    page.totalCount = res.data.totalCount
  }
  )
}

const onSubmit = () => {
  console.log('submit!')
}

// 定义数据类型接口
interface WarehouseItem {
  warehouseType: number
  warehouse_InOrOutCount: number
  total_Price: number
  warehouse_Code: string
  reviewTime: string
  warehousing_Type: string
  warehouse_Name: string
  reviewer: string
  createUse: string
  [key: string]: any // 允许其他属性
}

// 计算入库数量和入库金额总和
const totalInboundCount = computed(() => {
  return (tableData.value as WarehouseItem[])
    .filter(item => item.warehouseType == 1) // 只统计入库数据
    .reduce((sum, item) => sum + (item.warehouse_InOrOutCount || 0), 0)
})

const totalInboundAmount = computed(() => {
  return (tableData.value as WarehouseItem[])
    .filter(item => item.warehouseType == 1) // 只统计入库数据
    .reduce((sum, item) => sum + (item.total_Price || 0), 0)
    .toFixed(2)
})
</script>

<style scoped>
/* 主容器 */
.warehouse-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  padding: 24px 32px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
  color: #667eea;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0;
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  color: #6c757d;
  font-size: 16px;
  font-weight: 500;
  padding: 8px 16px;
  background: rgba(108, 117, 125, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(108, 117, 125, 0.2);
}

/* 主要内容区域 */
.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 搜索卡片 */
.search-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.search-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.card-header .el-icon {
  font-size: 20px;
  color: #667eea;
}

.search-form {
  padding: 8px 0;
}

.search-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
}

.custom-input,
.custom-select,
.custom-date-picker {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.custom-input:hover,
.custom-select:hover,
.custom-date-picker:hover {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.custom-input:focus-within,
.custom-select:focus-within,
.custom-date-picker:focus-within {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.search-btn,
.reset-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  margin-right: 8px;
}

.search-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.reset-btn {
  background: #f8f9fa;
  border: 2px solid #dee2e6;
  color: #6c757d;
}

.reset-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
  transform: translateY(-2px);
}

/* 统计卡片 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.stats-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.stats-content {
  padding: 24px;
  position: relative;
  z-index: 2;
}

.stats-number {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #2c3e50;
}

.stats-label {
  font-size: 14px;
  color: #2c3e50;
  font-weight: 500;
}

.stats-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 24px;
  opacity: 0.2;
  color: #2c3e50;
}

.inbound-card {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  border-left: 4px solid #667eea;
}

.inbound-card .stats-number {
  color: #667eea;
}

.inbound-card .stats-label {
  color: #2c3e50;
}

.inbound-amount-card {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  border-left: 4px solid #667eea;
}

.inbound-amount-card .stats-number {
  color: #667eea;
}

.inbound-amount-card .stats-label {
  color: #2c3e50;
}

/* 表格卡片 */
.table-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.table-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.table-card .card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.export-btn,
.refresh-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.export-btn {
  background: linear-gradient(135deg, #28a745, #20c997);
  border: none;
}

.export-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.3);
}

.refresh-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

/* 表格样式 */
.custom-table {
  border-radius: 8px;
  overflow: hidden;
}

.custom-table :deep(.el-table__header-wrapper) {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}

.custom-table :deep(.el-table__header) {
  color: #2c3e50;
  font-weight: 600;
}

.custom-table :deep(.el-table__body) {
  color: #2c3e50;
}

.custom-table :deep(.el-table__row) {
  color: #2c3e50;
}

.inbound-count {
  color: #667eea;
  font-weight: 600;
}

.outbound-count {
  color: #ff6b6b;
  font-weight: 600;
}

.inbound-amount {
  color: #667eea;
  font-weight: 700;
}

.outbound-amount {
  color: #ff6b6b;
  font-weight: 700;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.custom-pagination {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 8px 16px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .warehouse-container {
    padding: 16px;
  }

  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }

  .page-header {
    padding: 20px 24px;
  }

  .page-title {
    font-size: 24px;
  }
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-section {
    grid-template-columns: 1fr;
  }

  .header-actions {
    flex-direction: column;
    gap: 8px;
  }

  .export-btn,
  .refresh-btn {
    width: 100%;
  }
}
</style>